package com.zkh360.service.message.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;

import com.zkh360.service.message.constant.Constants;
import com.zkh360.service.message.constant.ErrorCode;
import com.zkh360.service.message.controller.base.BaseController;
import com.zkh360.service.message.exceptions.BusinessException;
import com.zkh360.service.message.model.BaseResponse;
import com.zkh360.service.message.model.Pager;
import com.zkh360.service.message.model.SysAuthoritiesResourcesVO;
import com.zkh360.service.message.model.SysAuthorityVO;
import com.zkh360.service.message.model.SysResourcesVO;
import com.zkh360.service.message.model.SysUserVO;
import com.zkh360.service.message.service.ResourceService;

import lombok.extern.slf4j.Slf4j;

/**
 * 资源信息
 * 
 * @author chuanxi.zhao
 *
 */
@Controller
@Slf4j
public class ResourceConrtroller extends BaseController {

	@Autowired
	private ResourceService resourceService;

	/**
	 * 获取资源信息（主要是URL地址）
	 * 
	 * @return
	 */
	@RequestMapping("/resources")
	@PreAuthorize("hasRole('ROLE_ADMIN')")
	public String getResourcesByUser(Model model, Integer currentPage) {
		log.info("获取资源信息");
		try {
			Pager pager = new Pager();
			pager.setCurrentPage(currentPage);
			pager.setPageSize(Constants.PAGE_SIZE);
			
			SysUserVO sysUsers = new SysUserVO();
			sysUsers.setUser_account(getUserName());
			List<SysResourcesVO> sysResourceList = resourceService.getResourcesByUser(sysUsers, null, pager);

			int totalCount = resourceService.getResourceCount(sysUsers);

			// 设置分页信息
			setPager(currentPage, totalCount, pager);

			model.addAttribute("resources", sysResourceList);
			model.addAttribute("pager", pager);
		} catch (NumberFormatException nfe) {
			log.error("添加资源信息异常", nfe.getMessage());
		}

		return "resources";
	}

	/**
	 * 获取用户可见菜单
	 * 
	 * @return
	 */
	@GetMapping("/menus")
	public void getMenus(HttpServletResponse response) throws IOException {
		log.info("获取资源信息");
		// 通过登录名获取用户信息
		Pager pager = new Pager();
		pager.setCurrentPage(1);
		pager.setPageSize(100);

		SysUserVO sysUsers = new SysUserVO();
		sysUsers.setUser_account(getUserName());
		List<SysResourcesVO> sysResourceList = resourceService.getResourcesByUser(sysUsers, 1, pager);
		// 整理成parent->child
		Map<Integer, List<SysResourcesVO>> parentChild = new HashMap<>();
		sysResourceList.forEach(sysResource -> {
			if (parentChild.containsKey(sysResource.getParent_id())) {
				parentChild.get(sysResource.getParent_id()).add(sysResource);
			} else {
				List<SysResourcesVO> childList = new ArrayList<>();
				childList.add(sysResource);
				parentChild.put(sysResource.getParent_id(), childList);
			}
		});
		// 获取一级目录
		List<SysResourcesVO> firstLevelMenus = sysResourceList.stream()
				.filter(sysResource -> sysResource.getParent_id() == 0).collect(Collectors.toList());
		// 设置二级目录
		firstLevelMenus.forEach(sysResource -> {
			sysResource.setChilds(parentChild.get(sysResource.getResource_id()));
		});

		BaseResponse<List<SysResourcesVO>> result = BaseResponse.sucess(ErrorCode.CODE_SUCESS, "success",
				firstLevelMenus);
		writeJSON(response, result);
	}

	/**
	 * 新增资源信息（主要是URL地址）
	 * 
	 * @throws IOException 读写异常
	 */
	@PostMapping("/resource/add")
	@PreAuthorize("hasRole('ROLE_ADMIN')")
	public void addResource(@RequestBody SysResourcesVO sysResourcesVo, HttpServletResponse response)
			throws IOException {
		log.info("添加资源信息");
		// 前端返回
		BaseResponse<String> result = BaseResponse.sucess(ErrorCode.CODE_SUCESS, "success", "添加成功");
		try {
			resourceService.addResource(sysResourcesVo);
		} catch (BusinessException e) {
			log.error("添加资源信息异常", e.getErrorMsg());
			result = BaseResponse.fail(e.getErrorCode(), "fail", e.getErrorMsg());
		}

		writeJSON(response, result);
	}

	/**
	 * 获取用户可见一级菜单
	 * 
	 * @return
	 */
	@GetMapping("/firstMenus")
	@PreAuthorize("hasRole('ROLE_ADMIN')")
	public void getFirstMenus(HttpServletResponse response) throws IOException {
		log.info("获取资源信息");
		SysResourcesVO sysResourcesVo = new SysResourcesVO();
		sysResourcesVo.setResource_level(1);
		List<SysResourcesVO> sysResourceList = resourceService.getResources(sysResourcesVo);
		BaseResponse<List<SysResourcesVO>> result = BaseResponse.sucess(ErrorCode.CODE_SUCESS, "success",
				sysResourceList);
		writeJSON(response, result);
	}

	/**
	 * 获取资源信息 主要是点击修改按钮获取详情
	 * 
	 * @throws IOException IO异常
	 */
	@GetMapping("/resource")
	public void getResource(Integer resourceId, HttpServletResponse response) throws IOException {
		log.info("获取资源信息详情");
		SysResourcesVO sysResourcesVo = new SysResourcesVO();
		sysResourcesVo.setResource_id(resourceId);
		List<SysResourcesVO> sysResourceList = resourceService.getResources(sysResourcesVo);
		BaseResponse<SysResourcesVO> result = BaseResponse.sucess(ErrorCode.CODE_SUCESS, "success", null);

		if (sysResourceList.size() == 0) {
			result = BaseResponse.fail(ErrorCode.CODE_FAILURE, "查询不到该目录信息！", null);
		} else if (sysResourceList.size() == 1) {
			result.setResult(sysResourceList.get(0));
		} else {
			result = BaseResponse.fail(ErrorCode.CODE_FAILURE, "查询到多个目录信息！", null);
		}

		writeJSON(response, result);
	}

	/**
	 * 获取资源信息 主要是点击修改按钮获取详情
	 * 
	 * @throws IOException IO异常
	 */
	@GetMapping("/resource/authority/list")
	public void getResourceByAuthority(Integer authorityId, HttpServletResponse response) throws IOException {
		log.info("获取资源信息详情");
		SysResourcesVO sysResourcesParams = new SysResourcesVO();
		sysResourcesParams.setResource_level(2);
		List<SysResourcesVO> allSysResourceList = resourceService.getResources(sysResourcesParams);

		SysAuthorityVO sysAuthorityVo = new SysAuthorityVO();
		sysAuthorityVo.setAuthority_id(authorityId);
		List<SysResourcesVO> sysResourceList = resourceService.getResourcesByAuthority(sysAuthorityVo);

		Map<Integer, String> resourceMap = new HashMap<>();
		sysResourceList.forEach(sysResource -> {
			resourceMap.put(sysResource.getResource_id(), "");
		});

		allSysResourceList.forEach(sysResource -> {
			if (resourceMap.containsKey(sysResource.getResource_id())) {
				sysResource.setIfInuse(true);
			}
		});
		BaseResponse<List<SysResourcesVO>> result = BaseResponse.sucess(ErrorCode.CODE_SUCESS, "success",
				allSysResourceList);
		writeJSON(response, result);
	}

	/**
	 * 修改资源权限信息
	 * 
	 * @throws IOException 读写异常
	 */
	@PostMapping("/resource/authority/edit")
	@PreAuthorize("hasRole('ROLE_ADMIN')")
	public void editResourceByAuthority(@RequestBody List<SysAuthoritiesResourcesVO> authorityResourcesVoList,
			HttpServletResponse response) throws IOException {
		log.info("配置资源权限操作");
		// 前端返回
		BaseResponse<String> result = BaseResponse.sucess(ErrorCode.CODE_SUCESS, "success", "添加成功");
		try {
			resourceService.editResourceByAuthority(authorityResourcesVoList);
		} catch (BusinessException e) {
			log.error("添加资源信息异常", e.getErrorMsg());
			result = BaseResponse.fail(e.getErrorCode(), "fail", e.getErrorMsg());
		}

		writeJSON(response, result);
	}

	/**
	 * 获取资源信息 主要是点击修改按钮获取详情
	 * 
	 * @throws IOException IO异常
	 */
	@GetMapping("/resource/delete")
	@PreAuthorize("hasRole('ROLE_ADMIN')")
	public void deleteResource(Integer resourceId, HttpServletResponse response) throws IOException {
		log.info("删除资源信息详情");
		BaseResponse<String> result = BaseResponse.sucess(ErrorCode.CODE_SUCESS, "success", "删除成功");

		try {
			resourceService.deleteResource(resourceId);
		} catch (BusinessException e) {
			log.error("删除资源信息异常", e.getErrorMsg());
			result = BaseResponse.fail(e.getErrorCode(), "fail", e.getErrorMsg());
		}

		writeJSON(response, result);
	}

	/**
	 * 修改资源信息（主要是URL地址）
	 * 
	 * @throws IOException 读写异常
	 */
	@PostMapping("/resource/edit")
	@PreAuthorize("hasRole('ROLE_ADMIN')")
	public void editResource(@RequestBody SysResourcesVO sysResourcesVo, HttpServletResponse response)
			throws IOException {
		log.info("修改资源信息");
		// 前端返回
		BaseResponse<String> result = BaseResponse.sucess(ErrorCode.CODE_SUCESS, "success", "添加成功");
		try {
			resourceService.editResource(sysResourcesVo);
		} catch (BusinessException e) {
			log.error("添加资源信息异常", e.getErrorMsg());
			result = BaseResponse.fail(e.getErrorCode(), "fail", e.getErrorMsg());
		}

		writeJSON(response, result);
	}

}
